﻿using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using System.Linq;
using System.Web;

namespace RestaurantWebService
{
    public class Menu
    {
        private static volatile Menu instance;
        private static object syncRoot = new Object();

        private List<Meal> meals = new List<Meal>();

        private Menu() 
        {
            populateMenu();
        }

        public static Menu Instance
        {
            get 
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new Menu();
                        }
                    }
                }
                return instance;
            }
        }

        public List<Meal> Meals
        {
            get { return meals; }
        }

        public Meal getMealByNumber(int mealNumber)
        {
            foreach (Meal meal in meals)
            {
                if (meal.MealNumber == mealNumber)
                {
                    return meal;
                }
            }
            return null;
        }

        private void populateMenu()
        {
            DatabaseManager dbManager = new DatabaseManager();
            MySqlConnection conn = null;
            MySqlDataReader reader = null;
            try
            {
                conn = dbManager.getConnection();
                reader = dbManager.getDataReader("SELECT * FROM meal;", conn);
                while (reader.Read())
                {
                    Meal meal = new Meal();
                    meal.MealNumber = (int) reader["mealNumber"];
                    meal.Name = (string) reader["name"];
                    meal.Price = (float) reader["price"];
                    meal.TimeToProduce = (int) reader["timeToProduce"];
                    meal.IsAvailable = (bool) reader["isAvailable"];
                    meals.Add(meal);
                }
            }
            catch (MySqlException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                DatabaseManager.close(reader);
                DatabaseManager.close(conn);
            }
        }
    }
}